<template>
  <div>
       <TableLayout form-title="">
            <div slot="form-title" class="table-title"></div>
            <el-form :model="formInline" class="formInline" label-width="70px" slot="form">
                 <el-row :gutter="41">
                    <el-col :span="8">
                         <el-form-item label="打卡日期"> 
                            <el-row>
                                <el-col :span="11">
                                    <start-date v-model="formInline.startDate" :clearable="false" :picker-options="formInline.pickerOptions1" :end-date-options.sync="formInline.pickerOptions2" :state="false"></start-date>
                                </el-col>
                                <el-col :span="2" align="center">至</el-col>
                                <el-col :span="11">
                                    <end-date v-model="formInline.endDate" :clearable="false" :picker-options="formInline.pickerOptions2" :start-date-options.sync="formInline.pickerOptions1" :state="false"></end-date>
                                </el-col>
                           </el-row>   
                           
                        </el-form-item>  
                    </el-col>
                    <el-col :span="8" v-if="this.schoolType == 0">
                        <el-form-item label="年级">
                            <el-select v-model="formInline.grade" placeholder="请选择年级" style="width:100%" @change="eventClass">
                                <el-option v-for="item in formInline.gradeList" :key="item.pId" :label="item.sName" :value="item.pId"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8" >
                        <el-form-item label="班级">
                            <el-select v-model="formInline.className" placeholder="请选择班级" style="width:100%">
                                <el-option v-for="item in formInline.classNameList" :key="item.classId" :label="item.classNickName" :value="item.classId"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                 </el-row>
                 <el-row :gutter="41">
                    <el-col :span="8">
                        <el-form-item label="学生姓名">
                            <el-input v-model="formInline.name" placeholder="请输入学生姓名"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                 <div class="top-line">
                    <el-button type="primary" class="top-btn" @click="onSubmit">查询</el-button>
                </div>
            </el-form>
            <div class="table-title" slot="table-title">
                <div class="btnPosition">
                    <el-button slot="reference" @click="btnExport">导出</el-button>
                </div>
            </div>
            <el-table :data="AnnounceList" border style="width: 100%"  ref="multipleTable" v-loading="loading">
                <el-table-column align="center" label="学生姓名">
                     <template scope = "scope">
                        {{!scope.row.name ? '--' : scope.row.name}}
                    </template>
                </el-table-column>
                 <el-table-column align="center" label="年级">
                     <template scope = "scope">
                        {{!scope.row.gradeName ? '--' :scope.row.gradeName}}
                    </template>
                </el-table-column>
                 <el-table-column align="center" label="班级">
                     <template scope = "scope">
                        {{!scope.row.className ? '--' : scope.row.className}}
                    </template>
                </el-table-column>
                 <el-table-column align="center" label="应打卡次数">
                     <template scope = "scope">
                        {{scope.row.total}}
                    </template>
                </el-table-column>
                <el-table-column align="center" label="无记录次数">
                     <template scope = "scope">
                        {{scope.row.noRecord}}
                    </template>
                </el-table-column>
                <el-table-column align="center" label="正常次数">
                     <template scope = "scope">
                        {{scope.row.nomal}}
                    </template>
                </el-table-column>
                <el-table-column align="center" label="迟到次数">
                     <template scope = "scope">
                        {{scope.row.late}}
                    </template>
                </el-table-column>
                 <el-table-column align="center" label="早退次数">
                     <template scope = "scope">
                        {{scope.row.leave}}
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination-container" style="text-align:right">
                <el-pagination layout="total, sizes, prev, pager, next, jumper" :total="listQuery.total" :current-page.sync="listQuery.page" :page-sizes="config.pageSizes" :page-size="config.pageSize" @size-change="handleSizeChange" @current-change="handleCurrentChange">
                </el-pagination>
            </div>
        </TableLayout>
  </div>
</template>
<script>
import TableLayout from 'components/TableLayout';
import startDate from 'components/Datepicker/startDate';
import endDate from 'components/Datepicker/endDate';
import { mapState, mapActions, mapGetters } from 'vuex';
import {
  pageStudentCheckinfoCount,
  findSchoolFirstAttendance
} from 'api/attendanceManage';
import { getGradeList, getClassList } from 'api/studentMange';
export default {
    name: 'schoolRegion',
    components: { TableLayout, endDate, startDate },
    data() {
        return {
            formInline: {
                name: '',
                grade: '',
                gradeList: [],
                className: '',
                classNameList: [],
                attendanceTime: null,
                startDate: '',
                endDate: '',
                pickerOptions1: {
                    disabledDate: time => {
                        let attendanceTime = new Date(this.formInline.attendanceTime).getTime() - 3600 * 1000 *24;
                        if (attendanceTime) {
                            return time.getTime() < attendanceTime;
                        }
                    }
                },
                pickerOptions2: {
                    disabledDate: time => {
                        return time.getTime() > Date.now(); 
                    }
                }
            },
            AnnounceList: [],
            listQuery: {
        // 分页
                page: 1,
                total: 0
            },
            loading: false
        };
    },
    computed: {
        ...mapState({
            config: state => state.config.table,
            cacheUpdated: state => state.app.cacheUpdated // 局部刷新列表
        }),
        ...mapGetters([
            'uid',
            'schoolName',
            'schoolId',
            'cardIsOpen',
            'schoolType',
            'token'
        ])
    },
  // 列表页添加watch：
    watch: {
    // 局部刷新列表
        cacheUpdated(val) {
            //console.log(val, '----------')
            if (this.cardIsOpen == 1 && this.formInline.startDate) {

                val && this.searchFetchData();
            }
        }
    },

    created() {
        if (this.cardIsOpen == 1) {
            this.getTime();
        } else {
            this.$message('该服务未开通！');
            let end = new Date();
            let start = new Date();
            end.setTime(end.getTime() - 3600 * 1000 * 24);
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            this.formInline.startDate = start;
            this.formInline.endDate = end;
        }

    // 判断是否是培训学校
        if (this.schoolType == 1) {

            this.eventClass(null);
        }
    },
    methods: {
        ...mapActions(['ChangePageSize']),
        onSubmit() {
            this.listQuery.page = 1;
            this.searchFetchData();
        },
        getTime() {
            findSchoolFirstAttendance(this.schoolId, '0')
        .then(data => {
            if (data.data.content) {
                this.formInline.attendanceTime = data.data.content.attendanceTime;
                //console.log(this.formInline.attendanceTime, '1111');
            }
        })
        .then(() => {
            this.initDate();
        })
        .then(() => {
            if (this.formInline.attendanceTime) {
                this.searchFetchData();
            }
        })
        .catch(Error => {
            //console.log('没有设置时间');
        })
        },
    // 查询列表
        searchFetchData() {
            this.loading = true;
            pageStudentCheckinfoCount(
        this.fifterDate(this.formInline.startDate),
        this.fifterDate(this.formInline.endDate),
        this.schoolId,
        this.formInline.className,
        this.formInline.grade,
        this.formInline.name,
        this.listQuery.page,
        this.config.pageSize
      )
        .then(data => {
            this.loading = false;
            this.AnnounceList = data.data.content.list;
            this.listQuery.total = data.data.content.pagination.total;
        })
        .catch(Error => {
            this.loading = false;
        });
        },
    // 分页
        handleSizeChange(val) {
            this.listQuery.page = 1;
            this.ChangePageSize(val);
            this.searchFetchData();
        },
        handleCurrentChange(val) {
            this.listQuery.page = val;
            this.searchFetchData();
        },
    // 设置初始时间
        initDate() {
            let end = new Date();
            let start = new Date();
      // 是否大于开通时间
            if (this.formInline.attendanceTime) {
                //console.log(this.formInline.attendanceTime);
                let newDate = new Date(this.formInline.attendanceTime).getTime();
                if (newDate < start.getTime() - 3600 * 1000 * 24 * 7) {
                    start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                    end.setTime(end.getTime() - 3600 * 1000 * 24);
                } else {
          // 假设不满7天的话 且正好是当天的话
                    if (newDate < start.getTime() - 3600 * 1000 * 24) {
                        start.setTime(newDate);
                        end.setTime(end.getTime() - 3600 * 1000 * 24);
                    } else {
                        start.setTime(newDate);
                        end.setTime(newDate);
                    }
                }
            } else {
                end.setTime(end.getTime() - 3600 * 1000 * 24);
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            }
      //
            this.formInline.startDate = start;
            this.formInline.endDate = end;

      // 获取年级
            getGradeList(this.schoolId).then(data => {
                this.formInline.gradeList = data.data.content;
                this.formInline.gradeList.unshift({ sName: '请选择' });
            });
        },
    // 获取班级
        eventClass(val) {
            //console.log(val)
            if (val || val === null) {
                getClassList(val, this.schoolId).then(data => {
                    this.formInline.className = '';
                    this.formInline.classNameList = data.data.content;
                    this.formInline.classNameList.unshift({ classNickName: '请选择' });
                });
            } else {
                this.formInline.className = '';
                this.formInline.classNameList= []
                this.formInline.classNameList.unshift({ classNickName: '请选择' });
            }
        },
    // 返回年月日时分秒
        fifterDate(date) {
            if (typeof date === 'string') {
                return date;
            } else {
                let month = this.addZero(date.getMonth() + 1 + '');
                let day = this.addZero(date.getDate() + '');
                return `${date.getFullYear()}-${month}-${day}`;
            }
        },
    // 补0
        addZero(str) {
            if (typeof str === 'string') {
                return str.length > 1 ? str : '0' + str;
            }
        },
        btnExport() {
            let token = this.token,
                schoolId = this.schoolId,
                searchDate = this.fifterDate(this.formInline.startDate),
                endDay = this.fifterDate(this.formInline.endDate),
                classId = this.formInline.className || '',
                gradeId = this.formInline.grade || '';
            //console.log(classId, gradeId)
            if (this.listQuery.total !== 0) {
                window.location.href = `${
          LOCAL_API.ly
        }/checkinfo/exportStudentCheckinfoCount?token=${token}&schoolId=${schoolId}&startDay=${searchDate}&endDay=${endDay}&classId=${
          classId
        }&gradeId=${gradeId}&studentName=${
          this.formInline.name
        }`;
            } else {
                this.$message.warning('无数据，无法导出！');
            }
        }
    }
};
</script>